package pers.vic.boot.security.shiro;

import org.apache.shiro.ShiroException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import pers.vic.boot.base.model.BaseResponse;

import javax.servlet.http.HttpServletRequest;


/**
 * @description: 后台管理系统统一异常处理
 * @author: Vic.xu
 * @date: 2020年1月13日 上午11:20:45
 */
@RestControllerAdvice
@ConditionalOnClass(HttpServletRequest.class)
public class AuthGlobalExceptionHandler {

    private static Logger logger = LoggerFactory.getLogger(AuthGlobalExceptionHandler.class);

    /**
     * @description: SHIRO 未授权异常
     * @author: Vic.xu
     * @date: 2020年1月13日 上午11:52:46
     */
    @ExceptionHandler(value = {UnauthenticatedException.class, UnauthorizedException.class})
    public BaseResponse<?> shiroPermissionExceptionHandler(HttpServletRequest request, Exception e) {
        logger.error("无访问{}权限", request.getRequestURI(), e);
        return BaseResponse.error(403, "无访问权限");
    }

    /**
     * @description: SHIRO 未登陆异常
     * @author: Vic.xu
     * @date: 2020年1月13日 上午11:52:46
     */
    @ExceptionHandler(value = {AuthorizationException.class, AuthenticationException.class})
    public BaseResponse<?> shiroUnauthenticatedExceptionHandler(HttpServletRequest request, ShiroException e) {
        logger.error("访问{}需要先登陆", request.getRequestURI(), e);
        return BaseResponse.error(401, "请先登陆");
    }

}
